/**
 * Module:
 * Description: 商品控制器
 * Author: xsq
 * Date: 2023/05/05 15:44:37
 * LastEditAuthor: xsq
 * LastEditTime: 2023/05/05 15:44:37
 */

const commodityModel = require('../model/commodity');
const dictModel = require('../model/dict');
const { getDictsParse, commodityList } = require('../services/commodity');
const { saveSqlParse, updateSqlParse, saveAllSqlParse, decrypt } = require('../common/utils');
const { connect } = require("../model/index");


/**
 * 获取所有字典
 * @method: post
 * @param {*} ctx
 * @param {*} next
 */
const getDicts = async (ctx, next) => {
  const query = ctx.request.body;

  const dicts = await getDictsParse(query);

  ctx.body = {
    data: dicts,
    code: 200,
    msg: '查询成功',
  };
  await next();
};

/**
 * 获取商品列表
 * @method: post
 * @param {*} ctx
 * @param {*} next
 */
const getCommodityList = async (ctx, next) => {
  const query = ctx.request.body;
  const pageSize = Number(query.pageSize || 10);
  const pageNum = Number(query.pageNum || 1) - 1;

  const queryParams = query.params || {};
  // queryParams.category = query.category; // 类目
  // queryParams.auth_status = query.auth_status; // 认证状态
  // queryParams.fans_age = query.fans_age; // 粉丝年龄
  // queryParams.fans_bias = query.fans_bias; // 粉丝偏向
  // queryParams.fans_num = query.fans_num; // 粉丝数量
  // queryParams.shop_status = query.shop_status; // 橱窗状态
  // queryParams.has_violation = query.has_violation; // 有无违规
  // queryParams.chart_real = query.chart_real; // 星图实名
  // queryParams.chart_auth = query.chart_auth; // 星图权限
  // queryParams.live_auth = query.live_auth; // 直播权限
  // queryParams.price = query.price; // 价格

  const { list, pageCount, total } = await commodityList(queryParams, {
    pageSize,
    pageNum
  });
  ctx.body = {
    data: {
      datas: list,
      pageNum: pageNum + 1,
      pageSize: pageSize,
      pageCount: pageCount,
      total: total,
    },
    code: 200,
    msg: '查询成功',
  };
  await next();
};

/**
 * TODO:获取商品详情
 * @method: get
 * @param {*} ctx
 * @param {*} next
 */
const commodityById = async (ctx, next) => {
  const query = ctx.request.query;
  // const id = query.id;
  const id = decrypt(query.id.replace(/\~/g, '/'));

  let res = {};
  const database = commodityModel.TABLE_NAME;
  let [rows, fields] = await connect.query(`select * from ${database} where id = ?`, [
    id,
  ]);
  if (rows[0]) {
    const commodityId = rows[0].id;

    let [fileList] = await connect.query(`select * from ${database}_image where commodity_id = ?`, [
      commodityId,
    ]);
    rows[0].fans_age = String(rows[0].fans_age).split(',');
    // console.log(rows[0])
    res = rows[0];
    res.fileList = fileList;
  }
  // console.log(rows[0]);
  ctx.body = {
    data: res,
    code: 200,
    msg: '查询成功',
  };
  await next();
};

/**
 * 获取商品分类
 * @method: get
 * @param {*} ctx
 * @param {*} next
 */
const getCommodityCate = async (ctx, next) => {
  const query = ctx.request.query;

  const database = commodityModel.TABLE_NAME;
  let [rows, fields] = await connect.query(`select * from ${database}_cate where status = ? order by order_num ASC`, [1]);

  ctx.body = {
    data: rows,
    code: 200,
    msg: '查询成功',
  };
  await next();
};

/**
 * 添加账号
 * @method: post
 * @param {*} ctx
 * @param {*} next
 */
const addCommodity = async (ctx, next) => {
  const query = ctx.request.body;
  const fileList = query.fileList;
  const saveData = {
    title: query.title,
    account_id: query.account_id, // 商品id
    number: query.number,
    price: query.price,
    fans_price: query.fans_price,
    phone: query.phone, // 用户手机号
    up_num: query.up_num, // 点赞数量
    min_price: query.min_price, // 最低价
    wechat: query.wechat, // 微信号
    category: query.category,
    auth_status: query.auth_status,
    fans_bias: query.fans_bias,
    fans_age: query.fans_age.join(','), // 粉丝年龄
    fans_num: query.fans_num,
    shop_status: query.shop_status,
    has_violation: query.has_violation,
    chart_real: query.chart_real,
    chart_auth: query.chart_auth,
    live_auth: query.live_auth,
    is_hot: query.is_hot || 0,
    status: query.status || 0,
    commodity_cate_id: query.commodity_cate_id, // 分类id
    admin_user_id: query.admin_user_id, // 上架人
    service_cate: query.service_cate, // 抖音所属分类
    sale_status: query.sale_status, // 出售状态

    reputation_score: query.reputation_score, // 信誉分状态
    docking_status: query.docking_status, // 对接状态
    work_dou: query.work_dou, // 抖音作品dou+
    live_dou: query.live_dou, // 抖音直播dou+
    dou_account: query.dou_account, // 抖音dou+户头
    fen_strip: query.fen_strip, // 快手粉条
    is_change_real: query.is_change_real, // 是否更换实名
    remark: query.remark, // 备注
    visit_time: query.visit_time || null, // 回访时间
    is_minor_refund: query.is_minor_refund, // 是否有未成年退款，0 否，1 是
    activity_level: query.activity_level, // 活跃度
    reason_remark: query.reason_remark, // 下架原因

    create_time: Math.floor(Date.now() / 1000),
    update_time: Math.floor(Date.now() / 1000),
  };

  const { fields, values } = saveSqlParse(saveData);

  const database = commodityModel.TABLE_NAME;
  const connection = await connect.getConnection();

  let [account] = await connect.query(
    `select id from ${database} where account_id = ?`,
    [saveData.account_id]
  );
  if (account[0]) {
    ctx.throw({
      data: null,
      code: 400,
      message: '商品id已经添加',
    });
  }

  try {
    // 开启事务
    await connection.beginTransaction();

    const [rows, field] = await connection.query(
      `
        INSERT INTO ${database}
        (${fields.join(',')})
        VALUES (${values.join(',')})
      `
    );
    for (let i = 0; i < fileList.length; i++) {
      fileList[i].url = fileList[i].path;
      fileList[i].commodity_id = rows.insertId; // 最新插入的商品id
      fileList[i].file_name = fileList[i].name;
    }

    // const imgValList = [];
    // for (let i = 0; i < fileList.length; i++) {
    //   imgValList.push(`('${fileList[i].path}','${fileList[i].commodity_id}','${fileList[i].name}')`);
    // }

    // await connection.query(
    //   `
    //     INSERT INTO ${database}_image(url,commodity_id,file_name)
    //     VALUES ${imgValList.join(',')};
    //   `
    // );

    if (fileList.length > 0) {
      const { fields: imgFields, valList } = saveAllSqlParse(fileList, ['url', 'commodity_id', 'file_name']);
      await connection.query(
        `
          INSERT INTO ${database}_image(${imgFields.join(',')})
          VALUES ${valList.join(',')};
        `
      );
    }

    await connection.commit();
  } catch (err) {
    await connection.rollback();
    ctx.throw(new Error('hello' + err));
  } finally {
    // connection.releaseConnection();
    connection.release();
  }

  ctx.body = {
    data: null,
    code: 200,
    msg: '操作成功',
  };
  await next();
};

/**
 * 修改账号
 * @method: post
 * @param {*} ctx
 * @param {*} next
 */
const updateCommodity = async (ctx, next) => {
  const query = ctx.request.body;
  const commodityId = query.id;
  const fileList = query.fileList || [];
  const saveData = {
    title: query.title,
    account_id: query.account_id, // 商品id
    number: query.number,
    price: query.price,
    fans_price: query.fans_price,
    phone: query.phone, // 用户手机号
    up_num: query.up_num, // 点赞数量
    min_price: query.min_price, // 最低价
    wechat: query.wechat, // 微信号
    category: query.category,
    auth_status: query.auth_status,
    fans_bias: query.fans_bias,
    fans_age: query.fans_age.join(','), // 粉丝年龄
    fans_num: query.fans_num,
    shop_status: query.shop_status,
    has_violation: query.has_violation,
    chart_real: query.chart_real,
    chart_auth: query.chart_auth,
    live_auth: query.live_auth,
    // is_hot: query.is_hot,
    // status: query.status || 1,
    commodity_cate_id: query.commodity_cate_id, // 分类id
    service_cate: query.service_cate, // 抖音所属分类
    sale_status: query.sale_status, // 出售状态

    reputation_score: query.reputation_score, // 信誉分状态
    docking_status: query.docking_status, // 对接状态
    work_dou: query.work_dou, // 抖音作品dou+
    live_dou: query.live_dou, // 抖音直播dou+
    dou_account: query.dou_account, // 抖音dou+户头
    fen_strip: query.fen_strip, // 快手粉条
    is_change_real: query.is_change_real, // 是否更换实名
    remark: query.remark, // 备注
    visit_time: query.visit_time || null, // 回访时间
    is_minor_refund: query.is_minor_refund, // 是否有未成年退款，0 否，1 是
    activity_level: query.activity_level, // 活跃度
    reason_remark: query.reason_remark, // 下架原因

    update_time: Math.floor(Date.now() / 1000),
  };

  const sqlArr = updateSqlParse(saveData);
  console.log(sqlArr);

  const database = commodityModel.TABLE_NAME;
  const connection = await connect.getConnection();

  try {
    // 开启事务
    await connection.beginTransaction();

    await connection.query(
      `
        UPDATE ${database}
        SET ${sqlArr.join(',')}
        WHERE id = ?
      `,
      [Number(commodityId)]
    );

    // TODO:删除原图
    await connection.query(
      `
        DELETE FROM ${database}_image
        where commodity_id = ?
      `,
      [commodityId]
    );

    // NOTE:添加新图
    // const imgValList = [];
    // for (let i = 0; i < fileList.length; i++) {
    //   imgValList.push(`('${fileList[i].path}','${commodityId}','${fileList[i].name}')`);
    // }

    // await connection.query(
    //   `
    //     INSERT INTO ${database}_image(url,commodity_id,file_name)
    //     VALUES ${imgValList.join(',')};
    //   `
    // );

    if (fileList.length > 0) {
      for (let i = 0; i < fileList.length; i++) {
        fileList[i].url = fileList[i].path;
        fileList[i].commodity_id = commodityId; // 最新插入的商品id
        fileList[i].file_name = fileList[i].name;
      }
  
      const { fields: imgFields, valList } = saveAllSqlParse(fileList, ['url', 'commodity_id', 'file_name']);
      await connection.query(
        `
          INSERT INTO ${database}_image(${imgFields.join(',')})
          VALUES ${valList.join(',')};
        `
      );
    }

    await connection.commit();
  } catch (err) {
    await connection.rollback();
    ctx.throw(new Error(err));
  } finally {
    // connection.releaseConnection();
    connection.release();
  }

  ctx.body = {
    data: {},
    code: 200,
    msg: '操作成功',
  };
  await next();
};

/**
 * 修改账号热门状态
 * @method: post
 * @param {*} ctx
 * @param {*} next
 */
const changeCommodityHot = async (ctx, next) => {
  const query = ctx.request.body;
  const commodityId = query.id;
  const saveData = {
    is_hot: query.is_hot,
    update_time: Math.floor(Date.now() / 1000)
  };

  const sqlArr = updateSqlParse(saveData);

  const database = commodityModel.TABLE_NAME;
  const connection = await connect.getConnection();

  try {
    // 开启事务
    await connection.beginTransaction();

    await connection.query(
      `
        UPDATE ${database}
        SET ${sqlArr.join(',')}
        WHERE id = ?
      `,
      [Number(commodityId)]
    );

    await connection.commit();
  } catch (err) {
    await connection.rollback();
    ctx.throw(new Error(err));
  } finally {
    // connection.releaseConnection();
    connection.release();
  }

  ctx.body = {
    data: {},
    code: 200,
    msg: '操作成功',
  };
  await next();
};

/**
 * 修改账号上架状态
 * @method: post
 * @param {*} ctx
 * @param {*} next
 */
const changeCommodityStatus = async (ctx, next) => {
  const query = ctx.request.body;
  const commodityId = query.id;
  const saveData = {
    status: query.status
  };

  const sqlArr = updateSqlParse(saveData);

  const database = commodityModel.TABLE_NAME;
  const connection = await connect.getConnection();

  try {
    // 开启事务
    await connection.beginTransaction();

    await connection.query(
      `
        UPDATE ${database}
        SET ${sqlArr.join(',')}
        WHERE id = ?
      `,
      [Number(commodityId)]
    );

    await connection.commit();
  } catch (err) {
    await connection.rollback();
    ctx.throw(new Error(err));
  } finally {
    // connection.releaseConnection();
    connection.release();
  }

  ctx.body = {
    data: {},
    code: 200,
    msg: '操作成功',
  };
  await next();
};

/**
 * 删除账号
 * @method: get
 * @param {*} ctx
 * @param {*} next
 */
const deleteCommodityById = async (ctx, next) => {
  const query = ctx.request.query;
  const id = query.id;

  const database = commodityModel.TABLE_NAME;
  const connection = await connect.getConnection();

  try {
    // 开启事务
    await connection.beginTransaction();

    await connection.query(
      `
        DELETE FROM ${database}
        where id = ?
      `,
      [id]
    );
    await connection.commit();
  } catch(err) {
    await connection.rollback();
    ctx.throw(new Error(err));
  } finally {
    // connection.releaseConnection();
    connection.release();
  }

  ctx.body = {
    data: {},
    code: 200,
    msg: '操作成功',
  };
  await next();
};


module.exports = {
  getCommodityList,
  commodityById,
  getDicts,
  getCommodityCate,
  addCommodity,
  updateCommodity,
  deleteCommodityById,
  changeCommodityHot,
  changeCommodityStatus
};
